package main

import (
	"flag"
	"fmt"
	"generatorserver/internal/gcs"
	"generatorserver/module"
	"os"
	"os/signal"
	"runtime"
	"runtime/pprof"
	"syscall"

	log "github.com/sirupsen/logrus"
)

var (
	version = "1.0.2"
)

func init() {
	// 启动参数的配置文件
	flag.StringVar(&confFile, "c", "/etc/config/cloud.yaml", "path of service start config file")
	flag.StringVar(&featureFile, "f", "/etc/config/feature.yaml", "path of feature file")
	flag.Parse()
}

func main() {
	if runtime.GOOS == "windows" {
		confFile = confFile[1:]
		featureFile = featureFile[1:]
	}
	DoInitLibs()
	//module的逻辑初始
	module.InitLogicFromMain()
	//以上初始失败会panic终止
	log.Infof("start %s service, version[%s] ...", gcs.AppName, version)

	waitForSignal()
}

func waitForSignal() {
	c := make(chan os.Signal, 1)
	// Handle interrupt for graceful shutdown
	signal.Notify(c, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
	for {
		// Block until a signal is received.
		s := <-c
		fmt.Println("Got signal:", s)
		switch s {
		// kill -3 1
		case syscall.SIGQUIT:
			// how can one send a 'kill' signal to process on windows?
			dumpGoRoutinesInfo()
		default:
			return
		}
	}
}

func dumpGoRoutinesInfo() {
	log.Info("current goroutine count:", runtime.NumGoroutine())
	// use DEBUG=2, to dump stack like golang dying due to an unrecovered panic.
	pprof.Lookup("goroutine").WriteTo(os.Stdout, 2)
}
